/*
*  Copyright 2019-2025 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.account.rest;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import me.zhengjie.annotation.Log;
import lombok.RequiredArgsConstructor;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import me.zhengjie.modules.account.domain.AccountAc08;
import me.zhengjie.modules.account.domain.dto.AccountAc08QueryCriteria;
import me.zhengjie.modules.account.service.AccountAc08Service;
import me.zhengjie.util.ValidateUtil;
import me.zhengjie.utils.ExcelTemplateUtils;
import me.zhengjie.vo.Constant;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import me.zhengjie.utils.PageResult;
import org.springframework.web.multipart.MultipartFile;

/**
* @author lzw
* @date 2025-06-09
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "api")
@RequestMapping("/api/accountAc08")
public class AccountAc08Controller {

    private final AccountAc08Service accountAc08Service;

    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('accountAc08:list')")
    public void exportAccountAc08(HttpServletResponse response, AccountAc08QueryCriteria criteria) throws IOException {
        accountAc08Service.download(accountAc08Service.queryAll(criteria), response);
    }

    @PostMapping("queryAccountAc08")
    public ResponseEntity<PageResult<AccountAc08>> queryAccountAc08(@Validated @RequestBody AccountAc08QueryCriteria criteria){
        Page<Object> page = new Page<>(criteria.getPage(), criteria.getSize());
        return new ResponseEntity<>(accountAc08Service.queryAll(criteria,page),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增api")
    @ApiOperation("新增api")
    @PreAuthorize("@el.check('accountAc08:add')")
    public ResponseEntity<Object> createAccountAc08(@Validated @RequestBody List<AccountAc08> resources) throws Exception{
        accountAc08Service.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改api")
    @ApiOperation("修改api")
    @PreAuthorize("@el.check('accountAc08:edit')")
    public ResponseEntity<Object> updateAccountAc08(@Validated @RequestBody AccountAc08 resources) throws Exception {
        accountAc08Service.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除api")
    @ApiOperation("删除api")
    @PreAuthorize("@el.check('accountAc08:del')")
    public ResponseEntity<Object> deleteAccountAc08(@ApiParam(value = "传ID数组[]") @RequestBody List<AccountAc08> ids) throws IOException {
        accountAc08Service.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }


    @ApiOperation("下载模版")
    @GetMapping(value = "/downloadExcel")
    public void downloadExcel(HttpServletResponse response) throws IOException {

        ExcelTemplateUtils.exportFromTemplate(response, "excel/个人缴费明细录入模版.xls", "个人缴费明细录入模版");

    }

    @PostMapping("/importExcel")
    @Log("导入模版数据")
    @ApiOperation("导入模版数据")
    public ResponseEntity<Object> importExcel(@RequestPart("file") MultipartFile file, @RequestParam("aac001") String aac001, @RequestParam("aaz159") String aaz159, @RequestParam("aab001") String aab001 ) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("文件不能为空！");
        }

        StringBuilder stringBuilder = new StringBuilder();
        try {
            // 1. 使用 Hutool 读取 Excel（跳过第1行标题）
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream(), 0);

            // 2. 读取数据（从第2行开始）
            List<Map<String, Object>> dataList = reader.readAll();
            if(dataList.size()<=0){
                return ResponseEntity.status(500).body("导入失败：未获取到导入明细信息");
            }

            // 3. 解析并保存数据
            List<AccountAc08> listac08=new ArrayList<>();
            for (int i = 0; i < dataList.size(); i++) {
                Map<String, Object> row = dataList.get(i);
                AccountAc08 ac08 = new AccountAc08();
                ac08.setAac001(aac001);
                ac08.setAaz159(aaz159);
                ac08.setAab001(aab001);
                ac08.setAae140(Constant.AAE140_120_JGSYDWGZRYJBYLBX);

                String s = accountAc08Service.checkImport(row, i);
                if (s.length() > 0) {
                    stringBuilder.append(s);
                } else {

                    ac08.setAae003(new BigDecimal(row.get("对应费款所属期").toString()));

                    switch (row.get("应缴类型").toString()) {
                        case "正常应缴":
                            ac08.setAaa115(Constant.AAA115_10_ZCYJ); // 应缴类型
                            break;
                        case "缴费比例调整退收":
                            ac08.setAaa115(Constant.AAA115_21_JFBLDZTS); // 应缴类型
                            break;
                        case "缴费基数调整退收":
                            ac08.setAaa115(Constant.AAA115_22_JFJSDZTS); // 应缴类型
                            break;
                        case "缴费基数调整补缴":
                            ac08.setAaa115(Constant.AAA115_34_JFJSDZBJ); // 应缴类型
                            break;
                        case "缴费比例调整补缴":
                            ac08.setAaa115(Constant.AAA115_35_JFBLDZBJ); // 应缴类型
                            break;
                    }
                    ac08.setAab191(new BigDecimal(row.get("对应费款所属期").toString()).multiply(new BigDecimal(100)).add(BigDecimal.ONE)); // 到账日期

                    BigDecimal aae180 = new BigDecimal(row.get("人员缴费基数").toString());
                    BigDecimal aae797 = new BigDecimal(row.get("社平工资").toString());
                    BigDecimal aaa042 = new BigDecimal(row.get("单位缴费比例").toString());
                    BigDecimal aaa043 = new BigDecimal(row.get("单位划入比例").toString());
                    BigDecimal aaa045 = new BigDecimal(row.get("个人划入比例").toString());
                    BigDecimal aae819 = new BigDecimal(row.get("社平划入比例").toString());
                    String aae820 = row.get("类型").toString();
                    if("正常明细".equals(aae820)){
                        ac08.setAae820(Constant.AAC062_1_RYXCB);
                    }else  if("改个前年金试点划转明细".equals(aae820)){
                        ac08.setAae820(Constant.AAC062_9_QT);
                    }

                    if(BigDecimal.ZERO.compareTo(aae180)==0){//基数为0，则按照定额缴费生成定额明细

                        ac08.setAae180(aae180);
                        ac08.setAaa042(BigDecimal.ZERO);
                        ac08.setAaa043(BigDecimal.ZERO);
                        ac08.setAaa045(aaa045);
                        ac08.setAae080(aae180);
                        ac08.setAae081(aae180);
                        ac08.setAae083(aaa045);
                        ac08.setAae086(aae180);
                    }else{
                        ac08.setAae180(aae180);
                        ac08.setAaa042(aaa042);
                        ac08.setAaa043(aaa043);
                        ac08.setAaa045(aaa045);
                        ac08.setAae080(aae180.multiply(aaa042));
                        ac08.setAae081(aae180.multiply(aaa043));
                        ac08.setAae083(aae180.multiply(aaa045));
                        ac08.setAae086(aae797.multiply(aae819));

                    }
                    listac08.add(ac08);
                }
            }

            if(listac08.size()==dataList.size()){
                accountAc08Service.create(listac08);
                Map<String, Object> result = new HashMap<>();
                result.put("total", dataList.size());
                result.put("message", "导入成功");
                return ResponseEntity.ok().body(result);
            }else{
                return ResponseEntity.status(500).body("导入失败：" +stringBuilder.toString());
            }

        } catch (Exception e) {
            return ResponseEntity.status(500).body("导入失败：" + e.getMessage());
        }
    }

}
